package com.xjrsoft.module.customerTwo.EMP.dormitory_room.service.impl;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xjrsoft.core.constant.RedisKeyConstants;
import com.xjrsoft.core.tool.utils.StringUtil;
import com.xjrsoft.module.customerTwo.EMP.dormitory_room.entity.TDormitoryRoom;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.xjrsoft.core.tool.utils.CollectionUtil;

import java.util.*;

import com.xjrsoft.module.customerTwo.EMP.dormitory_room.dto.TDormitoryRoomListDto;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xjrsoft.common.page.ConventPage;
import java.util.List;
import java.util.Set;

import com.xjrsoft.module.customerTwo.EMP.dormitory_room.mapper.TDormitoryRoomMapper;
import com.xjrsoft.module.customerTwo.EMP.dormitory_room.service.ITDormitoryRoomService;
import com.xjrsoft.core.mp.base.BaseService;
import com.xjrsoft.core.tool.utils.Func;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 *  服务实现类
 *
 * @author dongxinhang
 * @since 2023-07-20
 */
@Service
@AllArgsConstructor
@Slf4j
public class TDormitoryRoomServiceImpl extends BaseService<TDormitoryRoomMapper, TDormitoryRoom> implements ITDormitoryRoomService {
	@Resource
	TDormitoryRoomMapper mapper;

	@Resource
	RedisTemplate<String,Object> redisTemplate;

	@Override
	public IPage<TDormitoryRoom> getPageList(TDormitoryRoomListDto pageListDto) {
		Wrapper<TDormitoryRoom> wrapper = Wrappers.<TDormitoryRoom>query().lambda()
				.eq(!StringUtil.isEmpty(pageListDto.getPart()), TDormitoryRoom::getPart, pageListDto.getPart())
				.eq(!StringUtil.isEmpty(pageListDto.getFloor()), TDormitoryRoom::getFloor, pageListDto.getFloor())
				.like(!StringUtil.isEmpty(pageListDto.getRoom_number()), TDormitoryRoom::getRoomNumber, pageListDto.getRoom_number())
				.eq(!StringUtil.isEmpty(pageListDto.getRoom_type()), TDormitoryRoom::getRoomType, pageListDto.getRoom_type())
				.like(!StringUtil.isEmpty(pageListDto.getEnergy_meter_number()), TDormitoryRoom::getEnergyMeterNumber, pageListDto.getEnergy_meter_number())
				.like(!StringUtil.isEmpty(pageListDto.getCold_water_meter_number()), TDormitoryRoom::getColdWaterMeterNumber, pageListDto.getCold_water_meter_number())
				.like(!StringUtil.isEmpty(pageListDto.getHot_water_meter_number()), TDormitoryRoom::getHotWaterMeterNumber, pageListDto.getHot_water_meter_number())
				.eq(!StringUtil.isEmpty(pageListDto.getStatus()), TDormitoryRoom::getStatus, pageListDto.getStatus());
		return this.page(ConventPage.getPage(pageListDto), wrapper);
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public String addTDormitoryRoom(TDormitoryRoom tDormitoryRoom) {
		String tDormitoryRoomId = IdWorker.get32UUID();
		tDormitoryRoom.setId(tDormitoryRoomId);
		boolean isSuccess = this.save(tDormitoryRoom);
		if(isSuccess){
			if(tDormitoryRoom.getBedNumber()>tDormitoryRoom.getUsedBedNumber()){
				redisTemplate.opsForValue().set(RedisKeyConstants.CACHE_ROOM_LEFT+tDormitoryRoom.getRoomNumber(),tDormitoryRoom.getBedNumber()-tDormitoryRoom.getUsedBedNumber());
			}
			return tDormitoryRoomId;
		}
		return null;
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public boolean updateTDormitoryRoom(String id, TDormitoryRoom tDormitoryRoom) {
		tDormitoryRoom.setId(id);
		//更新时删除原有缓存然后更新
		redisTemplate.delete(RedisKeyConstants.CACHE_ROOM_LEFT+tDormitoryRoom.getRoomNumber());
		boolean isSuccess = this.updateById(tDormitoryRoom);
		if(isSuccess){
			if(tDormitoryRoom.getBedNumber()>tDormitoryRoom.getUsedBedNumber()){
				redisTemplate.opsForValue().set(RedisKeyConstants.CACHE_ROOM_LEFT+tDormitoryRoom.getRoomNumber(),tDormitoryRoom.getBedNumber()-tDormitoryRoom.getUsedBedNumber());
			}
			return true;
		}
		return false;
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public boolean delete(String ids) {
		List<String> idList = Func.toStrList(ids);
		deleteByids(idList);
		return this.removeByIds(idList);
	}

	@Transactional(rollbackFor=Exception.class)
	public boolean deleteByids(List<String> list){
		ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
		for(String id:list){
			TDormitoryRoom room = getById(id);
			if(valueOperations.get(RedisKeyConstants.CACHE_ROOM_LEFT+room.getRoomNumber())!=null){
				redisTemplate.delete(RedisKeyConstants.CACHE_ROOM_LEFT+room.getRoomNumber());
			}
		}
		return true;
	}
	/**
	* Title: getRoomLeft
	* @description 启动时缓存加载房间信息
	* @createTime  2023-12-05 9:31
	* @param
	* @return void
	*/
	@Override
	@PostConstruct
	public void getRoomLeft(){
		List<TDormitoryRoom> rooms = mapper.selectList(null);

		Set<String> keys = redisTemplate.keys(RedisKeyConstants.CACHE_ROOM_LEFT+"*");
		//删除所有缓存
		if(keys!=null){
			redisTemplate.delete(keys);
		}
		//写入缓存
		for(TDormitoryRoom room:rooms){
			if(room.getBedNumber()!=null){
				if(room.getBedNumber()>room.getUsedBedNumber()){
					redisTemplate.opsForValue().set(RedisKeyConstants.CACHE_ROOM_LEFT+room.getRoomNumber(),room.getBedNumber()-room.getUsedBedNumber());
				}
			}
		}
		//log.info("剩余房间数量缓存更新");
	}

	@Override
	public boolean upDateUsedRoomByRoomNum(String roomNum, Integer num) throws Exception {
		TDormitoryRoom room = getByRoomNumber(roomNum);
		if(room.getUsedBedNumber()+num<0){
			throw new Exception("使用床位无法小于0");
		}
		if(room.getBedNumber() >= room.getUsedBedNumber()+num){
			room.setUsedBedNumber(room.getUsedBedNumber()+num);
			return updateById(room);
		}
		throw new Exception("入住人数超出");
	}

	@Override
	public boolean roomNumberExist(String roomNumber,String id) {
		Wrapper<TDormitoryRoom> wrapper = Wrappers.<TDormitoryRoom>query().lambda()
				.eq(true,TDormitoryRoom::getRoomNumber,roomNumber);
		List<TDormitoryRoom> list = this.list(wrapper);
		if(StringUtils.isNotBlank(id)){		//修改
			for(TDormitoryRoom tDormitoryRoom : list){
				if(!id.equals(tDormitoryRoom.getId())){
					return true;
				}
			}
		}else if(CollectionUtil.isNotEmpty(list)){	//新增
			return true;
		}
		return false;
	}

	@Override
	public Map<String,Map<String,String>> getFloorData() {
		List<Map> floorList = this.getBaseMapper().getFloorData();
		if(CollectionUtil.isNotEmpty(floorList)){
			Map<String,Map<String,String>> result = new HashMap<>();
			for (Map floorMap : floorList){
				String parentCode = Func.toStr(floorMap.get("parent_code"));
				Map one = result.get(parentCode);
				if(CollectionUtil.isEmpty(one)) {
					one = new HashMap();
				}
				one.put(Func.toStr(floorMap.get("name")),Func.toStr(floorMap.get("code")));
				result.put(parentCode,one);
			}
			return result;
		}
		return null;
	}

	@Override
	public List<String> getRoomNumberList(Set<String> roomNumberSet) {
		return this.getBaseMapper().getRoomNumberList(roomNumberSet);
	}
/**
* Title: getByRoomNumber
* @description 通过房间号码获得数据
* @createTime  2023-09-21 16:16
* @param roomNumber
* @return com.xjrsoft.module.customerTwo.EMP.dormitory_room.entity.TDormitoryRoom
*/
	@Override
	public TDormitoryRoom getByRoomNumber(String roomNumber){
		return this.getBaseMapper().getByRoomNumber(roomNumber);
	}
}